package cn.edu.scau.cmi.ema.service;

import cn.edu.scau.cmi.ema.base.CmiPagination;
import cn.edu.scau.cmi.ema.domain.Adultertype;
import cn.edu.scau.cmi.ema.domain.Event;
import cn.edu.scau.cmi.ema.service.base.CmiEmaService;
import cn.edu.scau.cmi.ema.util.CmiSqlUtil;
import org.hibernate.Session;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Projections;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.Query;
import java.util.*;
@Service("AdultertypeService")
@Transactional

public class AdultertypeServiceImpl extends CmiEmaService implements AdultertypeService {
	public AdultertypeServiceImpl() {
	}

	@Transactional
	public Adultertype saveAdultertype(Adultertype adultertype) {
		Set<Event> existingEventsForEvent = new HashSet<Event>();

		Set<Event> selectedEventsForEvent = adultertype.getEventsForAdultertype();

		if (adultertype.getId() == null) {

			Adultertype existingAdultertype = adultertypeDAO.findAdultertypeByPhysicalPrimaryKey(adultertype.getName());

			if (isEquals(adultertype, existingAdultertype)) {
				return existingAdultertype;
			}

			adultertype = adultertypeDAO.store(adultertype);
			adultertypeDAO.flush();

			for (Event relatedEvent : selectedEventsForEvent) {
				relatedEvent.getAdultertypesForEvent().add(adultertype);
				eventDAO.store(relatedEvent);
			}
		} else {
			Adultertype existingAdultertype = adultertypeDAO.findAdultertypeByPrimaryKey(adultertype.getId());

			existingEventsForEvent = existingAdultertype.getEventsForAdultertype();

			Set<Event> prepareDeleteEventsForEvent = new HashSet<Event>();
			Set<Event> prepareAddEventsForEvent = new HashSet<Event>();

			prepareDeleteEventsForEvent.addAll(selectedEventsForEvent);
			prepareDeleteEventsForEvent.addAll(existingEventsForEvent);

			prepareAddEventsForEvent.addAll(selectedEventsForEvent);
			prepareAddEventsForEvent.addAll(existingEventsForEvent);

			prepareDeleteEventsForEvent.removeAll(selectedEventsForEvent);
			prepareAddEventsForEvent.removeAll(existingEventsForEvent);

			for (Event relatedEvent : prepareAddEventsForEvent) {

				relatedEvent.getAdultertypesForEvent().add(existingAdultertype);
				eventDAO.store(relatedEvent);
			}

			for (Event relatedEvent : prepareDeleteEventsForEvent) {

				relatedEvent.getAdultertypesForEvent().remove(existingAdultertype);
				eventDAO.store(relatedEvent);
			}
			adultertype = adultertypeDAO.store(adultertype);
			adultertypeDAO.flush();
		}

		eventDAO.flush();
		return adultertype;
	}

	public void deleteAdultertype(Adultertype adultertype) {
		adultertypeDAO.remove(adultertype);
		adultertypeDAO.flush();
	}

	@Transactional
	public void deleteAdultertypes(Set<Integer> deleteAdultertypesId) {
		Query query = adultertypeDAO.createNamedQuery("deleteAdultertypesById", -1, -1);
		query.setParameter(1, deleteAdultertypesId);
		query.executeUpdate();
	}

	@Transactional
	public Set<Adultertype> loadAdultertypes() {
		return adultertypeDAO.findAllAdultertypes();

	}

	@Transactional
	public Set<Adultertype> loadReferenceAdultertypes(Set<Adultertype> adultertypes) {
		Iterator<Adultertype> adultertypesIterator = adultertypes.iterator();
		Set<Adultertype> referencedAdultertypes = new HashSet<>();
		while (adultertypesIterator.hasNext()) {
			Adultertype currentAdultertype = adultertypesIterator.next();

			if (!currentAdultertype.getEventsForAdultertype().isEmpty()) {
				referencedAdultertypes.add(currentAdultertype);
				continue;
			}
		}
		return referencedAdultertypes;
	}

	public Set<Adultertype> loadAdultertypesByIdSet(Set<Integer> adultertypeIdSet) {

		Iterator<Integer> adultertypeIdIterator = adultertypeIdSet.iterator();
		Set<Adultertype> adultertypeSet = new HashSet<>();
		while (adultertypeIdIterator.hasNext()) {
			Integer id = adultertypeIdIterator.next();
			Adultertype currentAdultertype = adultertypeDAO.findAdultertypeById(id);
			adultertypeSet.add(currentAdultertype);
		}
		return adultertypeSet;
	}

	@Transactional
	public List<Adultertype> findAllAdultertypes(Integer startResult, Integer maxRows) {
		return new java.util.ArrayList<Adultertype>(adultertypeDAO.findAllAdultertypes(startResult, maxRows));
	}

	@Transactional
	public Adultertype findAdultertypeByPrimaryKey(Integer id) {
		return adultertypeDAO.findAdultertypeByPrimaryKey(id);
	}

	@Transactional
	public Integer countAdultertypes() {
		return ((Long) adultertypeDAO.createQuerySingleResult("select count(o) from Adultertype o").getSingleResult())
				.intValue();
	}

	@Transactional
	public Integer countAdultertypes(CmiPagination page) {
		String sql = CmiSqlUtil.createCountHql(page, Adultertype.class);
		return ((Long) adultertypeDAO.createQuerySingleResult(sql).getSingleResult()).intValue();
	}

	/**
	 * search for name with ajax
	 *
	 */
	@Transactional
	public Integer countAdultertypesByName(String queryName) {
		Query query = adultertypeDAO.createNamedQuery("countAdultertypesByName", -1, -1);
		query.setParameter(1, queryName);
		return new Long((long) query.getSingleResult()).intValue();
	}

	@Transactional
	public Integer countAdultertypesByDetachedCriteria(CmiPagination page) {
		DetachedCriteria detachedCriteria = CmiSqlUtil.createDetachedCriteria(page, Adultertype.class);
		Session session = (Session) entityManager.getDelegate();
		detachedCriteria.setProjection(Projections.rowCount());
		return new Long((long) detachedCriteria.getExecutableCriteria(session).uniqueResult()).intValue();
	}

	public Map<String, ?> loadAdultertypeObjectReferencedSet(Adultertype adultertype) {
		HashMap<String, Object> objectReferencedSetMap = new HashMap<>();

		Set<Integer> eventsIds = new HashSet<Integer>();
		for (Event event : adultertype.getEventsForAdultertype()) {
			eventsIds.add(event.getId());
		}
		objectReferencedSetMap.put("eventsIds", eventsIds);

		return objectReferencedSetMap;
	}

	public Map<String, ?> loadAdultertypeClassReferencedSet(Adultertype adultertype) {
		HashMap<String, Object> classReferencedSetMap = new HashMap<>();
		classReferencedSetMap.put("events", eventDAO.findAllEvents());

		return classReferencedSetMap;
	}

	public boolean isEquals(Adultertype adultertype, Object obj) {
		if (obj == adultertype)
			return true;
		if (!(obj instanceof Adultertype))
			return false;
		Adultertype comparedAdultertype = (Adultertype) obj;
		if (!CheckPropertyEqual(adultertype.getName(), comparedAdultertype.getName())) {
			return false;
		}
		return true;
	}

	public static <T> boolean CheckPropertyEqual(T originProperty, T comparedProperty) {
		// 基本类型经过参数传递后会自动装箱
		String[] className = originProperty.getClass().getName().split("\\.");
		if (className[0].equals("java") && className[1].equals("math")) {
			return ((Comparable) originProperty).compareTo(comparedProperty) == 0 ? true : false;
		} else {
			return originProperty.equals(comparedProperty);
		}
	}
}

